//
//  DataBase.m
//  NewsReader
//
//  Created by blacksun on 11-2-17.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "DataBase.h"


@implementation Database

-(void) connection{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentPath = [paths objectAtIndex:0];
	NSString *dataFilePath = [documentPath stringByAppendingPathComponent:kSqlFilePath];
	
	if (sqlite3_open([dataFilePath UTF8String], &database) != SQLITE_OK) {
		sqlite3_close(database);
		NSAssert(0,@"Failed to open database");
	}
}
-(void) close{
	sqlite3_close(database);
}

/**
 aParams里的元素只接收NSString 和 NSNumber类型的变量
 */
-(void) excuteSql:(NSString *)aSql withParams:(NSArray *)aParams{
	sqlite3_stmt *statement;
	if (sqlite3_prepare_v2(database, [aSql UTF8String], -1, &statement, nil) != SQLITE_OK) {
		sqlite3_close(database);
		NSAssert(0,@"Error: failed to sqlite3_prepare_v2");
	}
	
	/*if (aParams) {
		for (int i=0; i<[aParams count]; i++) {
			if ([[aParams objectAtIndex:i] isKindOfClass:<#(Class)aClass#>]) {
				<#statements#>
			}
		}
	}*/
	
	if (sqlite3_step(statement) != SQLITE_DONE) {
		sqlite3_finalize(statement);
		sqlite3_close(database);
		//NSAssert(0,@"Error: failed to excute sql:(%@)",aSql);
	}
	sqlite3_finalize(statement);
}
-(sqlite3_stmt *) query:(NSString *)aSql withParams:(NSArray *)aParams{
	return nil;
}
-(void) finalizeStatement:(sqlite3_stmt *)aStmt{
	sqlite3_finalize(aStmt);
}
-(void) beginTransaction{
	sqlite3_exec(database,"BEGIN TRANSACTION",0,0,0);
}
-(void) commitTransaction{
	sqlite3_exec(database,"COMMIT",0,0,0);
}

+(void) createTables{
	sqlite3 *database ;
	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentPath = [paths objectAtIndex:0];
	NSString *dataFilePath = [documentPath stringByAppendingPathComponent:kSqlFilePath];
	
	if (sqlite3_open([dataFilePath UTF8String], &database) != SQLITE_OK) {
		sqlite3_close(database);
		NSAssert(0,@"Failed to open database");
	}
	
	
	char *errorMsg1;
	NSString *createSql1 = @"CREATE TABLE IF NOT EXISTS FEEDS(FEEDID INTEGER,SECTIONID TEXT,LAYOUTSCALE INTEGER,TITLE TEXT,AUTHOR TEXT,PUBDATE TEXT,CREATEDATE TEXT,DESCRIPTION TEXT,LINK TEXT,COMPLETE INTEGER,THUMB TEXT,INSERTDATE INTEGER ,PRIMARY KEY(FEEDID,SECTIONID))";
	if (sqlite3_exec(database, [createSql1 UTF8String], NULL, NULL, &errorMsg1) != SQLITE_OK) {
		sqlite3_close(database);
		//NSAssert(0,@"Error create table: %s",errorMsg1);
	}
	char *errorMsg2;
	NSString *createSql2 = @"CREATE TABLE IF NOT EXISTS CONTENTS(CONTENTID INTEGER PRIMARY KEY,FEEDID INTEFER,SECTIONID TEXT,HEIGTH INTEFER,WIDTH INTEFER,TYPE TEXT,SRC TEXT,CONTENT TEXT,INSERTDATE INTEGER)";
	if (sqlite3_exec(database, [createSql2 UTF8String], NULL, NULL, &errorMsg2) != SQLITE_OK) {
		sqlite3_close(database);
		//NSAssert(0,@"Error create table: %s",errorMsg2);
	}
	[createSql1 release];
	[createSql2 release];
	sqlite3_close(database);
}

@end
